package com.lituoxy.dialer.updata;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;


import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class CheckUpdata {
    private String TAG = "CheckUpdata";
    private final int UPDATA_NONEED = 0;
    private final int UPDATA_CLIENT = 1;
    private final int GET_UNDATAINFO_ERROR = 2;
    private final int SDCARD_NOMOUNTED = 3;
    private final int DOWN_ERROR = 4;
    private final static String PROJECT = "xicheng";
    private UpdataInfo info;
    private int localVersion;
    private Activity ac;

    public CheckUpdata(Activity ac) {
        this.ac = ac;
        this.ac.getClass().getName();
    }

    //-------------------------------------------------
    public void AutoUpdata() {
        try {
            localVersion = getVersionName();
            CheckVersionTask cv = new CheckVersionTask();
            new Thread(cv).start();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private int getVersionName() throws Exception {
        PackageManager packageManager = ac.getPackageManager();
        PackageInfo packInfo = packageManager.getPackageInfo(ac.getPackageName(),
                0);
        return packInfo.versionCode;
    }

    public class CheckVersionTask implements Runnable {
        InputStream is;
        boolean net = false;

        public void run() {
            do {
                try {
                    URL url = new URL("http://47.93.203.247/android/call_phone/lastver.txt");
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(5000);
                    conn.setRequestMethod("GET");
                    int responseCode = conn.getResponseCode();
                    if (responseCode == 200) {
                        is = conn.getInputStream();
                    }
                    info = UpdataInfoParser.getUpdataInfo(is);
                    System.out.println(info.getVersion() + "<---->" + localVersion);
                    if (Integer.valueOf(info.getVersion()) > localVersion) {
                        Message msg = new Message();
                        msg.what = UPDATA_CLIENT;
                        handler.sendMessage(msg);
                    } else {
                        Message msg = new Message();
                        msg.what = UPDATA_NONEED;
                        handler.sendMessage(msg);
                        // LoginMain();
                    }
                    net = true;
                } catch (Exception e) {
                    Message msg = new Message();
                    msg.what = GET_UNDATAINFO_ERROR;
                    handler.sendMessage(msg);
                    e.printStackTrace();
                }
                if (!net) {
                    try {
                        Thread.sleep(4000);
                    } catch (InterruptedException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }
            } while (!net);
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case UPDATA_NONEED:
                    //Toast.makeText(ac.getApplicationContext(), "不需要更新",Toast.LENGTH_SHORT).show();
                    break;
                case UPDATA_CLIENT:
                    showUpdataDialog();
                    break;
                case GET_UNDATAINFO_ERROR:
                    Toast.makeText(ac.getApplicationContext(), "获取服务器更新信息失败，重新获取中...", Toast.LENGTH_SHORT).show();
                    break;
                case DOWN_ERROR:
                    //Toast.makeText(ac.getApplicationContext(), "下载新版本失败", 1).show();
                    AutoUpdata();
                    break;
            }
        }
    };

    /*
   * 弹出对话框通知用户更新程序
   * 弹出对话框的步骤：
   *  1.创建alertDialog的builder.
   *  2.要给builder设置属性, 对话框的内容,样式,按钮
   *  3.通过builder 创建一个对话框
   *  4.对话框show()出来
   */
    protected void showUpdataDialog() {
        //AlertDialog.Builder builer = new Builder(ac);
        //builer.setTitle("版本升级");
        //builer.setMessage(info.getDescription());
        //当点确定按钮时从服务器上下载 新的apk 然后安装   ?
        //builer.setPositiveButton("ȷ��", new DialogInterface.OnClickListener() {
        //	public void onClick(DialogInterface dialog, int which) {
        Log.i(TAG, "下载apk,更新");
        //Toast.makeText(ac.getApplicationContext(), "发现新版本程序后台自动下载文件包", 1).show();
        downLoadApk();
        //	}
        //});
//			builer.setNegativeButton("ȡ��", new DialogInterface.OnClickListener() {
//				public void onClick(DialogInterface dialog, int which) {
//					// TODO Auto-generated method stub
//					//do sth
//				}
//			});
//			AlertDialog dialog = builer.create();
//			dialog.show();
    }

    /*
     *从服务器中下载APK
     */
    protected void downLoadApk() {
        final ProgressDialog pd;
        pd = new ProgressDialog(ac);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下载更新");
        pd.setCancelable(false);
        pd.show();
        new Thread() {
            @Override
            public void run() {
                try {
                    File file = HttpHelper.getFileFromServer(info.getDownloadUrl(), Environment.getExternalStorageDirectory().toString(), "updata.apk", pd);
                    sleep(3000);
                    installApk(file);
                } catch (Exception e) {
                    Message msg = new Message();
                    msg.what = DOWN_ERROR;
                    handler.sendMessage(msg);
                    e.printStackTrace();
                }
                pd.dismiss(); //结束掉进度条对话框
            }
        }.start();
    }

    //安装apk
    protected void installApk(File file) {
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //执行动作
        intent.setAction(Intent.ACTION_VIEW);
        //执行的数据类型
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        ac.startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}
